import type { FormRules } from 'element-plus'

export interface ValidationRule {
  required?: boolean
  message?: string
  trigger?: string | string[]
  min?: number
  max?: number
  pattern?: RegExp
  validator?: (rule: any, value: any, callback: any) => void
}

export function useFormRules() {
  // 常用验证规则
  const commonRules = {
    required: (message = '此项为必填项', trigger: string | string[] = 'blur'): ValidationRule => ({
      required: true,
      message,
      trigger
    }),

    email: (required = true, trigger: string | string[] = 'blur'): ValidationRule[] => {
      const rules: ValidationRule[] = []
      if (required) {
        rules.push({ required: true, message: '请输入邮箱地址', trigger })
      }
      rules.push({
        pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        message: '请输入正确的邮箱格式',
        trigger
      })
      return rules
    },

    phone: (required = true, trigger: string | string[] = 'blur'): ValidationRule[] => {
      const rules: ValidationRule[] = []
      if (required) {
        rules.push({ required: true, message: '请输入手机号', trigger })
      }
      rules.push({
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号格式',
        trigger
      })
      return rules
    },

    password: (minLength = 6, maxLength = 20, required = true, trigger: string | string[] = 'blur'): ValidationRule[] => {
      const rules: ValidationRule[] = []
      if (required) {
        rules.push({ required: true, message: '请输入密码', trigger })
      }
      rules.push({
        min: minLength,
        max: maxLength,
        message: `密码长度在 ${minLength} 到 ${maxLength} 个字符`,
        trigger
      })
      return rules
    },

    username: (minLength = 2, maxLength = 20, required = true, trigger: string | string[] = 'blur'): ValidationRule[] => {
      const rules: ValidationRule[] = []
      if (required) {
        rules.push({ required: true, message: '请输入用户名', trigger })
      }
      rules.push({
        min: minLength,
        max: maxLength,
        message: `用户名长度在 ${minLength} 到 ${maxLength} 个字符`,
        trigger
      })
      rules.push({
        pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
        message: '用户名只能包含字母、数字、下划线和中文',
        trigger
      })
      return rules
    },

    url: (required = true, trigger: string | string[] = 'blur'): ValidationRule[] => {
      const rules: ValidationRule[] = []
      if (required) {
        rules.push({ required: true, message: '请输入URL地址', trigger })
      }
      rules.push({
        pattern: /^https?:\/\/.+/,
        message: '请输入正确的URL格式',
        trigger
      })
      return rules
    },

    number: (min?: number, max?: number, required = true, trigger: string | string[] = 'blur'): ValidationRule[] => {
      const rules: ValidationRule[] = []
      if (required) {
        rules.push({ required: true, message: '请输入数字', trigger })
      }
      rules.push({
        pattern: /^\d+(\.\d+)?$/,
        message: '请输入有效的数字',
        trigger
      })
      if (min !== undefined || max !== undefined) {
        rules.push({
          validator: (rule: any, value: any, callback: any) => {
            const num = parseFloat(value)
            if (min !== undefined && num < min) {
              callback(new Error(`数值不能小于 ${min}`))
            } else if (max !== undefined && num > max) {
              callback(new Error(`数值不能大于 ${max}`))
            } else {
              callback()
            }
          },
          trigger
        })
      }
      return rules
    },

    confirmPassword: (passwordField = 'password', trigger: string | string[] = 'blur'): ValidationRule => ({
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请再次输入密码'))
        } else if (value !== rule.form[passwordField]) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger
    }),

    idCard: (required = true, trigger: string | string[] = 'blur'): ValidationRule[] => {
      const rules: ValidationRule[] = []
      if (required) {
        rules.push({ required: true, message: '请输入身份证号', trigger })
      }
      rules.push({
        pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        message: '请输入正确的身份证号格式',
        trigger
      })
      return rules
    }
  }

  // 创建表单规则
  const createFormRules = (ruleConfig: Record<string, ValidationRule | ValidationRule[]>): FormRules => {
    const rules: FormRules = {}
    Object.keys(ruleConfig).forEach(key => {
      const rule = ruleConfig[key]
      rules[key] = Array.isArray(rule) ? rule : [rule]
    })
    return rules
  }

  // 常用表单规则组合
  const userFormRules = (): FormRules => createFormRules({
    username: commonRules.username(),
    password: commonRules.password(),
    email: commonRules.email(false) // 邮箱非必填
  })

  const loginFormRules = (): FormRules => createFormRules({
    username: commonRules.required('请输入用户名'),
    password: commonRules.required('请输入密码')
  })

  const registerFormRules = (): FormRules => createFormRules({
    username: commonRules.username(),
    password: commonRules.password(),
    confirmPassword: commonRules.confirmPassword(),
    email: commonRules.email()
  })

  return {
    commonRules,
    createFormRules,
    userFormRules,
    loginFormRules,
    registerFormRules
  }
}